package demo.Thread;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/12-08-12-9:17
 * @Description：demo.Thread
 */
public class notifyDemo {
    //等待列表
    private static List<String> waitList = new LinkedList<>();
    //唤醒列表
    private static List<String> notifyList = new LinkedList<>();
    private static Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<50;i++){
            String threadName = Integer.toString(i);
            new Thread(() -> {
                synchronized (lock) {
                    String cthreadName = Thread.currentThread().getName();
                    System.out.println("线程 ["+cthreadName+"] 正在等待.");
                    waitList.add(cthreadName);
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("线程 ["+cthreadName+"] 被唤醒了.");
                    notifyList.add(cthreadName);
                }
            },threadName).start();
            TimeUnit.MILLISECONDS.sleep(50);
         }
        TimeUnit.SECONDS.sleep(1);
         for(int i=0;i<50;i++){
             synchronized (lock) {
              //notify调用一次仅可以唤醒一个线程，唤醒多个线程需要调用多次
                lock.notify();
                //TimeUnit.MILLISECONDS.sleep(10);
             }
             TimeUnit.MILLISECONDS.sleep(10);
         }
         TimeUnit.SECONDS.sleep(1);
         System.out.println("wait顺序:"+waitList.toString());
         System.out.println("唤醒顺序:"+notifyList.toString());
    }
}
